package com.earl.common.config;

import com.earl.common.util.IpConvert;
import com.earl.common.util.date.DateFormatType;
import com.earl.common.util.date.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * Controller 的所有方法在执行前后都会进入functionAccessCheck方法
 *
 * @author
 */

@Slf4j
public class BaseLogConfig {

    @Autowired
    ObjectMapper objectMapper;


    //@Around("execution(* com.sfc.bill.voucher.controller..*(..))")
    public Object functionAccessCheck(final ProceedingJoinPoint pjp) throws Throwable {
        try {
            log.info("------Begin-----------:" + DateUtil.now(DateFormatType.CN_YYYY_MM_DD_HH_MM_SS));
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            // 请求的IP
            String ip = IpConvert.getIpAddress(request);
            String url = request.getRequestURI();
            String targetName = pjp.getTarget().getClass().getName();
            String getMethod = request.getMethod();
            // 获取方法名
            String methodName = pjp.getSignature().getName();

            log.info("ip: {} url: {} targetName: {} getMethod: {}\tMethodName: {}",
                    ip, url, targetName, getMethod, methodName);

            // 获取输入参数
            String requestContent = "";
            List<Object> listArgs = Arrays.asList(pjp.getArgs());

            try {
                requestContent = (new ObjectMapper()).writeValueAsString(listArgs);
            } catch (Exception e) {
                log.error("请求参数解析错误");
            }

            log.info("Input args:" + requestContent);
            Object o = pjp.proceed();

            log.info("Output return :" + objectMapper.writeValueAsString(o));
            log.info("------End-----------:" + DateUtil.now(DateFormatType.CN_YYYY_MM_DD_HH_MM_SS));
            return o;
        } catch (Throwable e) {
            throw e;
        }
    }
}
